﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using RBS.Common;
using System.Web.UI.WebControls;

public class UploadFile
{
    private static string _rootPath = AppDomain.CurrentDomain.BaseDirectory + @"uploads\";// ConfigHelper.GetConfigString("UploadPath");
    private static   int _maxSize = Convert.ToInt32( ConfigHelper.GetConfigString("filemaxSize"));//上传文件字节限制
    private static readonly string _filter = ConfigHelper.GetConfigString("allowExtensions");


    //public static bool SaveFile(System.Web.UI.Page page, FileUpload fileUpload, out string outPath)
    //{
    //    outPath = "";
    //    try
    //    {
    //        string prePath = _rootPath.Trim();
    //        if (prePath.Substring(prePath.Length - 1, 1) != "/" && prePath.Substring(prePath.Length - 1, 1) != "\\")
    //        {
    //            prePath += "/" + DateTime.Today.ToString("yyyyMM");
    //        }
    //        else
    //        {
    //            prePath += DateTime.Today.ToString("yyyyMM");
    //        }
    //        FileOperate.CreateFloders(prePath, true);
    //        return SaveFile(page, prePath, fileUpload, out outPath);
    //    }
    //    catch(Exception ex)
    //    {
    //        MessageBox.Show(page, ex.Message);
    //    }
    //    return false;
    //}
    public static bool SaveFile(System.Web.UI.Page page, string perPath, FileUpload fu, out string outPath, out int fileSize)
    {
        fileSize = fu.PostedFile.ContentLength;
        return SaveFile(page, perPath, fu, out  outPath);
    }

    /// <summary>
    /// 保存文件
    /// </summary>
    /// <param name="perPath">当前目录</param>
    /// <param name="fu">文件上传控件</param>
    public static bool SaveFile(System.Web.UI.Page page, string perPath, FileUpload fu, out string outPath)
    {


        outPath = "";
        try
        {
            if (fu.FileName != string.Empty)
            {
                string fileName = fu.FileName;
                string preFileName = fileName.Substring(0, fileName.LastIndexOf("."));
                string fileExt = fileName.Substring(fileName.LastIndexOf(".")).ToLower();
                int fileSize = fu.PostedFile.ContentLength;

                //检查后缀名是否被允许
                string errMsg = string.Empty;
                string[] types = _filter.Split(',');
                bool isvalid = false;
                for (int j = 0; j < types.Length; j++)
                {
                    if (isvalid = fileExt == types[j].Trim()) break;
                }
                if (!isvalid)
                { errMsg += "Error，The file format can only be：" + _filter; }
                //检查大小
                if (fileSize > _maxSize && _maxSize != 0)
                { errMsg += "Error，File exceeds the specified size (in bytes)：" + _maxSize; }
                //返回错误
                if (errMsg != string.Empty)
                {
                    outPath = errMsg;
                    return false;
                }
                //保存更名
                string savefileName = DateTime.Now.ToString("yyyyMMddHHmmss") + fileExt;

                if (!Directory.Exists(_rootPath + perPath))
                {
                    Directory.CreateDirectory(_rootPath + perPath);
                }
                fu.SaveAs(_rootPath + perPath + "/" + savefileName);

                //创建缩略图

                //水印


                //插入到编辑器
                outPath = perPath + "/" + savefileName;
                return true;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(page, ex.Message);
        }
        return false;
    }

    /// <summary>
    /// 获取上传附件的引用HTML代码
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    public static string GetAttachmentHtml(string path)
    {
        string outPut = "";
        if (string.IsNullOrEmpty(path))
            return "无附件. ";
        string fileExt = path.Substring(path.LastIndexOf(".") + 1).ToLower();
        if (fileExt == "rar" || fileExt == "doc" || fileExt == "ppt" || fileExt == "xls" || fileExt == "docx" || fileExt == "pptx" || fileExt == "xlsx")
        {
            string fileName = path.Substring(path.LastIndexOf(@"/") + 14);
            outPut = string.Format("附件下载：<a href='{0}' target='_blank'>{1}</a>", path, fileName);
        }
        else
        {
            outPut = string.Format("<img src='{0}' alt='' />", path);
        }
        return outPut;
    }

}

